﻿using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;

namespace JoshuaOneEight.Services
{
	/// <summary>
	/// Data access service layer.
	/// </summary>
	public class DataContext
	{
		#region Constructors

		/// <summary>
		/// Hide the constructor since this is a singleton pattern and we don't want to expose
		/// being able to create multiple instances.
		/// </summary>
		private DataContext()
		{
		}

		#endregion Constructors

		#region DataContext Members

		/// <summary>
		/// Gets the singleton instance of the data context service.
		/// </summary>
		public static DataContext Instance
		{
			get
			{
				if( mInstance == null )
				{
					mInstance = new DataContext();
				}
				return mInstance;
			}
		}

		/// <summary>
		/// Gets a list of the verses. This will be null of the service hasn't been loaded.
		/// </summary>
		public List<Verse> Verses
		{
			get
			{
				return mVerses;
			}
		}

		/// <summary>
		/// Load the verses from the data file.
		/// </summary>
		public void Load()
		{
			// Extract the data file from the assembly if it is missing.
			if( !File.Exists( FILE_NAME ) )
			{
				Stream input = GetType().Assembly.GetManifestResourceStream( "JoshuaOneEight.verses.xml" );
				FileStream output = new FileStream( FILE_NAME, FileMode.Create );

				int length;
				byte[] buffer = new byte[8 * 1024];
				while( (length = input.Read( buffer, 0, buffer.Length )) > 0 )
				{
					output.Write( buffer, 0, length );
				}

				input.Close();
				output.Close();
			}

			// Serialize the file into memory.
			Stream stream = File.Open( FILE_NAME, FileMode.Open );
			XmlSerializer serializer = new XmlSerializer( typeof( List<Verse> ) );
			mVerses = (List<Verse>)serializer.Deserialize( stream );
			stream.Close();
		}

		/// <summary>
		/// Saves the current information to the data file.
		/// </summary>
		public void Save()
		{
			// Deserialize the information back to the file.
			Stream stream = File.Open( FILE_NAME, FileMode.Create );
			XmlSerializer serializer = new XmlSerializer( typeof( List<Verse> ) );
			serializer.Serialize( stream, mVerses );
			stream.Close();
		}

		#endregion DataContext Members

		#region Private Members

		private const string FILE_NAME = "verses.xml";
		private static DataContext mInstance;
		private List<Verse> mVerses;

		#endregion Private Members

	}
}

